package spouts;

import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;

import com.google.common.collect.Lists;
import com.twitter.hbc.ClientBuilder;
import com.twitter.hbc.core.Client;
import com.twitter.hbc.core.Constants;
import com.twitter.hbc.core.Hosts;
import com.twitter.hbc.core.HttpHosts;
import com.twitter.hbc.core.endpoint.StatusesFilterEndpoint;
import com.twitter.hbc.core.processor.StringDelimitedProcessor;
import com.twitter.hbc.httpclient.auth.Authentication;
import com.twitter.hbc.httpclient.auth.OAuth1;

public class StreamingTweetSpout extends BaseRichSpout {

    private Client hosebirdClient;

    private BlockingQueue<String> tweetQueue;

    private SpoutOutputCollector collector;

    @Override
    public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
        this.collector = collector;

        tweetQueue = new LinkedBlockingQueue<String>(Integer.valueOf((String) conf.get("tweetQueueSize")));

        final Authentication hosebirdAuth = new OAuth1("UrOfh5dlYvQfAmI4C5w1UA", "kX50wXRpA3CkXuwAFPwIpKdQlcugB4Kcs4mpblTa7g",
                "1344172676-cUM1a3mmRUYjft237wIXE3lQnhY9JsOnXc5QI4P", "CPF5mHYCiqr9D3RQ2uozF29zVkaDso7GvGncdZ2rM54");

        final Hosts hosebirdHosts = new HttpHosts(Constants.STREAM_HOST);
        ClientBuilder builder = new ClientBuilder();
        builder.name("Hosebird-Client-01");
        builder.hosts(hosebirdHosts);
        builder.authentication(hosebirdAuth);
        builder.endpoint(new StatusesFilterEndpoint().trackTerms(Lists.newArrayList(((String) conf.get("trackTerms")).split(","))));
        builder.processor(new StringDelimitedProcessor(tweetQueue));

        hosebirdClient = builder.build();
        hosebirdClient.connect();
    }

    @Override
    public void nextTuple() {
        try {
            final String tweet = tweetQueue.take();
            collector.emit(new Values(tweet));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("rawTweet"));
    }

    @Override
    public void close() {
        hosebirdClient.stop();
    }

}
